package com.zhny.aiot.rtu.flow.plugin;

import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.model.IRequestMessage;
import com.zhny.aiot.plugin.modbus.ModemEngine;
import com.zhny.aiot.plugin.modbus.device.ModemConfig;
import com.zhny.aiot.plugin.modbus.device.modbus.ModbusNumDevice;
import com.zhny.aiot.plugin.modbus.handler.model.ModemResponseMessage;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.TaskEntity;
import com.zhny.aiot.rtu.flow.plugin.model.FlowStoreEntry;
import io.netty.buffer.ByteBuf;

public class FlowDevice extends ModbusNumDevice<FlowStoreEntry> {
    public FlowDevice(ModemEngine engine, IDeviceFactory<ModemConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super(engine, factory, centerFacilities, entity);
    }

    @Override
    public FlowStoreEntry decode(ModemResponseMessage msg) {
        ByteBuf buf = msg.getData();
        Float totalFlow=buf.readFloat();
        Float totalHeat=buf.readFloat();
        Float totalCapacity=buf.readFloat();
        Float flow=buf.readFloat();
        Float waterSupplyTemperature=buf.readFloat();
        Float returnWaterTemperature=buf.readFloat();
        FlowStoreEntry entry = new FlowStoreEntry();
        entry.setFlow(String.format ("%.2f",flow));
        entry.setTotalFlow( String.format ("%.2f",totalFlow));
        entry.setTotalHeat ( String.format ("%.2f",totalHeat));
        entry.setTotalCapacity ( String.format ("%.2f",totalCapacity));
        entry.setWaterSupplyTemperature ( String.format ("%.2f",waterSupplyTemperature));
        entry.setReturnWaterTemperature ( String.format ("%.2f",returnWaterTemperature));
        logger.info ("rtu-flow[{}]",entry);
        return entry;
    }

    @Override
    public boolean checkError(ModemResponseMessage modemResponseMessage) {
        return modemResponseMessage.getData ().readableBytes () == 24;
    }

    @Override
    protected IRequestMessage getCommand(TaskEntity taskEntity) {
        return getFactory ().getRequestMessage (getConfig ());
    }

    @Override
    protected void disposable() {

    }
}
